package com.example.photo_sharing.page.others;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.photo_sharing.R;
import com.example.photo_sharing.global.App;
import com.example.photo_sharing.page.adapter.ImgEditAdapter;
import com.example.photo_sharing.tool.Impl.EditImpl;
import com.example.photo_sharing.tool.Impl.PhotoImpl;
import com.example.photo_sharing.tool.Impl.UserInfoSPImpl;
import com.example.photo_sharing.entity.FindListItem;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Edit extends AppCompatActivity {

    //控件
    private EditText edit_title;
    private EditText edit_content;
    private Button edit_add;
    private Button edit_upload;
    private Button edit_save;
    private Button edit_send;
    private RecyclerView recyclerView;

    private App app;
    private SharedPreferences sharedPreferences;
    private UserInfoSPImpl usp;
    private EditImpl edit;
    private PhotoImpl pt = new PhotoImpl();

    private ImgEditAdapter myadpater;


    private boolean signOfOld;
    private String userId;
    private FindListItem data;
    private String imageCode = "0";

    private Context context;

    //旧图片的urls
    private ArrayList<String> images_url = new ArrayList<>();
    private int numOfUrl = 0;

    //新图片的uris
    private ArrayList<String> images_uri = new ArrayList<>();
    //从草稿读取的url转为的file
    private List<File> old_images = new ArrayList<>();


    private int REQUEST_IMAGE_OPEN = 2;
    private int REQUEST_MANAGER_PERMISSION = 3;
    private int REQUEST_CODE_CAMERA = 4;

    private String path = "/storage/emulated/0/DCIM/";

    //底部弹窗
    private BottomSheetDialog bottomSheetDialog;
    //弹窗视图
    private View bottomView;

    private boolean SignOfUpload_newest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        SignOfUpload_newest = false;

        app = (App)getApplication();
        sharedPreferences = getSharedPreferences("userInfo",MODE_PRIVATE);

        edit = new EditImpl();

        usp = new UserInfoSPImpl(sharedPreferences);

        userId = usp.getUserId();

        requestManagerPermission();
        requestCameraPermission();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);

        context = this;

        //隐藏标题栏
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide(); //隐藏标题栏
        }

        Intent intent = getIntent();
        signOfOld = intent.getBooleanExtra("signOfOld",false);

        initKJ();

        if(signOfOld){
            //读取草稿的内容（由具体草稿传来）
            data = (FindListItem) intent.getSerializableExtra("data");
            images_url = (ArrayList<String>) data.getImageUrlList();
            edit_title.setText(data.getTitle()+"");
            edit_content.setText(data.getContent()+"");
            imageCode = data.getImageCode();
            numOfUrl = images_url.size();
            System.out.println(images_url);
            System.out.println("1111111111111111111"+images_url.size());
        if(imageCode != "0"){
                initRW();
            }
        }


    }

    private void initKJ(){
        edit_title = findViewById(R.id.edit_title);
        edit_content = findViewById(R.id.edit_content);
        edit_add = findViewById(R.id.edit_add);
        edit_upload = findViewById(R.id.edit_upload);
        edit_save = findViewById(R.id.edit_save);
        edit_send = findViewById(R.id.edit_send);
        recyclerView = findViewById(R.id.edit_images);

        edit_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomSheetDialog = new BottomSheetDialog(view.getContext());
                bottomView = getLayoutInflater().inflate(R.layout.activity_change_info_avatar_button, null);
                bottomSheetDialog.setContentView(bottomView);

                TextView tvTakePictures = bottomView.findViewById(R.id.changeAvatar_take_pictures);
                TextView tvOpenAlbum = bottomView.findViewById(R.id.changeAvatar_open_album);
                TextView tvCancel = bottomView.findViewById(R.id.changeAvatar_cancel);

                //拍照
                tvTakePictures.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        File file = new File(path);
                        if (!file.exists()) {
                            file.mkdir();
                        }
                        String fileName = setImgName() + ".jpg"; //图片的文件名
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        Uri photoUri = Uri.fromFile(new File(path + fileName));//记录图片的uri
                        FileProvider.getUriForFile(getApplicationContext(),getPackageName() + ".fileprovider",file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); //photoUri就是图片存储的位置

                        System.out.println("asdasdjaiosjdioa"+ photoUri);

                        startActivityForResult(intent, REQUEST_CODE_CAMERA);

                        System.out.println("131232");
                        bottomSheetDialog.cancel();
                    }
                });
                //打开相册
                tvOpenAlbum.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ImageView imgView = null;  //用于显示图片
                        //打开相册
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        //指定获取的是图片
                        intent.setType("image/*");
                        //设置允许多选
                        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                        //startActivityForResult()方法有两个参数，第一个参数为Intent，第二个参数为自定义的一个请求码，这个请求码会在onActivityResult()方法中被返回。
                        startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_IMAGE_OPEN);
                        bottomSheetDialog.cancel();

                    }
                });

                //取消
                tvCancel.setOnClickListener(v -> {
                    bottomSheetDialog.cancel();
                });

                bottomSheetDialog.show();
            }
        });

        //上传当前的图片
        edit_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(images_url.size() == 0 && images_uri.size() == 0){
                    Toast.makeText(Edit.this,"还没添加图片哦！",Toast.LENGTH_LONG).show();
                    return;
                }
                if(numOfUrl>0){
                    for(int i=0;i<images_url.size();i++){
                        try {
                            old_images.add(pt.getFile(images_url.get(i)+""));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println(old_images.size());
                for(int i=0;i<images_uri.size();i++){
                    old_images.add(pt.uriToFileApiQ(Uri.parse(images_uri.get(i)),context));
                }
                System.out.println(old_images.size());
                pt.uploadPhotos(old_images);
                app.setDelay(300);
                imageCode = pt.getImageCode();
                System.out.println(imageCode);
                Toast.makeText(Edit.this,"图片上传成功",Toast.LENGTH_LONG).show();
                SignOfUpload_newest = true;
            }
        });

        edit_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println(SignOfUpload_newest);
                String title = edit_title.getText()+"";
                String content = edit_content.getText()+"";

                if(images_uri.size()==0 && images_url.size()==0){
                    if(App.isEmpty(title) && App.isEmpty(content)){
                        Toast.makeText(Edit.this,"内容不可为空",Toast.LENGTH_LONG).show();
                        return;
                    }
                    else{
                        imageCode = "0";
                    }
                }
                else if(SignOfUpload_newest == false){
                    Toast.makeText(Edit.this,"当前图片未同步，请先点击上传",Toast.LENGTH_LONG).show();
                    return;
                }

                imageCode = pt.getImageCode();
                System.out.println("-----gattaca----"+imageCode);
                edit.editSaves(content,title,userId,imageCode);
                app.setDelay(300);
                Intent intent = new Intent(Edit.this,L_saves.class);
                startActivity(intent);
            }
        });


        edit_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println(SignOfUpload_newest);
                String title = edit_title.getText()+"";
                String content = edit_content.getText()+"";

                if(images_uri.size()==0 && images_url.size()==0){
                    if(title.length()==0 && content.length()==0){
                        Toast.makeText(Edit.this,"这里什么都没有",Toast.LENGTH_LONG).show();
                        return;
                    }
                    else{
                        System.out.println(imageCode);
                        imageCode = "0";
                    }
                }
                else if(SignOfUpload_newest == false){
                    Toast.makeText(Edit.this,"当前图片未同步，请先点击上传",Toast.LENGTH_LONG).show();
                    return;
                }
                edit.editSend(content,title,userId,imageCode);

                if(signOfOld){
                    edit.editDelete(userId,data.getId());
                    System.out.println("修改发送成功");
                }
                else{
                    System.out.println("发送成功");
                }
                app.setDelay(300);

                Toast.makeText(Edit.this,"发布成功",Toast.LENGTH_LONG).show();
            }
        });


    }

    private void initRW(){
        recyclerView = (RecyclerView)findViewById(R.id.edit_images);
        ArrayList<String> image = new ArrayList<>();
        image.addAll(images_url);
        image.addAll(images_uri);
        myadpater = new ImgEditAdapter(this, image);
        recyclerView.setAdapter(myadpater);
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));

        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL));

        myadpater.setOnItemClickListener(new ImgEditAdapter.OnItemClickListener() {

            @Override
            public void OnItemClick(View view, String data) {
                System.out.println("查看图片");

            }

            @Override
            public void OnDeleteClick(View view,int pos,String data) {
                //删除并且刷新
                SignOfUpload_newest = false;
                System.out.println(pos+"ffffffffffffffffffffffff"+data+"fffffffffffffffff"+numOfUrl);
                if(pos < numOfUrl && signOfOld){
                    images_url.remove(pos);
                    numOfUrl --;
                }
                else{
                    images_uri.remove(pos-numOfUrl);
                }
                initRW();
                Toast.makeText(Edit.this,"删除成功",Toast.LENGTH_LONG).show();
            }
        });
    }

    //申请文件管理权限
    private void requestManagerPermission() {
        //当系统在11及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 没文件管理权限时申请权限
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_MANAGER_PERMISSION);
            }
        }

    }

    private void requestCameraPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
            return;
        }
    }

    private String setImgName(){

        Date date =new Date(System.currentTimeMillis( ));

        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd_HHmmss");

        return "IMG_"+dateFormat.format(date);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //将选择的图片显示
        if(requestCode == REQUEST_IMAGE_OPEN && resultCode == Activity.RESULT_OK &&data !=null){
            //单张图片的选择
//            Uri uri = data.getData();
//            System.out.println(data+"");
//            System.out.println(uri+"");
//
//            images_uri.add(uri+"");
//            initRW();
            ClipData imageNames = data.getClipData();
            System.out.println(imageNames);
            if (imageNames != null){
                SignOfUpload_newest = false;
                for (int i=0; i<imageNames.getItemCount(); i++){
                    Uri imageUri = imageNames.getItemAt(i).getUri();
                    images_uri.add(imageUri.toString());
                    System.out.println(imageUri);
                }
                //uri = imageNames.getItemAt(0).getUri();
            }
            System.out.println(images_uri.size());
            initRW();
        }
        else if (resultCode == REQUEST_CODE_CAMERA) {
            System.out.println("相机666");
        }
        else if (requestCode == REQUEST_MANAGER_PERMISSION && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            //用户拒绝权限，重新申请
            if (!Environment.isExternalStorageManager()) {
                requestManagerPermission();
            }
        }
        else if (requestCode == REQUEST_CODE_CAMERA && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            //用户拒绝权限，重新申请
            if (!Environment.isExternalStorageManager()) {
                requestCameraPermission();
            }
        }
        else{
            System.out.println("相机669996");
        }

    }
}
